package rps.client.ui;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;

import rps.client.UIController;


/**
 * An Animator for move animations.
 * @author Jannis Dickmann
 *
 */
public abstract class Animator extends Thread {
	
	private int fromIndex;
	private int toIndex;
	private Image img;
	private AnimatorPanel ap;
	private long duration;
	private int steps;
	Dimension apSize = UIController.BOARD_DIMENSION;

	/**
	 * Instantiates a new Animator for move animations.
	 * @param fromIndex The figures position to start the animation.
	 * @param toIndex The figures position after the animation.
	 * @param img The figures image.
	 * @param ap The AnimatorPanel to draw at.
	 * @param apSize The AnimatorPanels dimension.
	 */
	public Animator(int fromIndex, int toIndex, Image img,
			AnimatorPanel ap, long duration, int steps) {
		super();
		this.fromIndex = fromIndex;
		this.toIndex = toIndex;
		this.img = img;
		this.ap = ap;
		this.duration = duration;
		this.steps = steps;
	}
	
	public void skywalker(){
		run();
	}

	@Override
	public void run() {
		
		int x = getCol(fromIndex) * (apSize.width / 7);
		int y = getRow(fromIndex) * (apSize.height / 6);
		
		int toX = getCol(toIndex) * (apSize.width / 7);
		int toY = getRow(toIndex) * (apSize.height / 6);
		
		int distX = toX - x;
		int distY = toY - y;
		
		int stepper = 0;
		
		ap.hideButton(fromIndex);
		ap.setAnimatorImage(img);
		
		while(stepper < steps){
			x += distX / steps;
			y += distY / steps;
			
			ap.drawAnimatorImage(new Point(x,y));
			
			stepper++;
			
			try{
				sleep(duration / steps);
			}
			catch(InterruptedException ex){
				ex.printStackTrace();
			}
		}
		
		ap.setAnimatorImage(null);
		
		callback();
		
	}
	
	/**
	 * A function to be called when the animation is done.
	 */
	public abstract void callback();
	
	/**
	 * Gets a row corresponding to an index.
	 * @param index The index.
	 * @return The corresponding row from 0 to 5.
	 */
	private int getRow(int index){
		return index/7;
	}
	
	/**
	 * Gets a column corresponding to an index.
	 * @param index The index.
	 * @return The corresponding column from 0 to 6.
	 */
	private int getCol(int index){
		return index%7;
	}

}
